package com.zdxlz.fcmp.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdxlz.fcmp.business.dto.ict.DeviceInfoDto;
import com.zdxlz.fcmp.business.dto.ict.TicketInfoDto;
import com.zdxlz.fcmp.business.entity.DeviceInfoEntity;
import com.zdxlz.fcmp.business.entity.TicketInfoEntity;
import com.zdxlz.fcmp.business.mapper.DeviceInfoMapper;
import com.zdxlz.fcmp.business.mapper.TicketInfoMapper;
import com.zdxlz.fcmp.business.service.ITicketInfoService;
import com.zdxlz.fcmp.business.vo.TicketInfoVo;
import com.zdxlz.fcmp.common.mybatis.enums.TicketStatusEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单信息表 服务实现类
 * </p>
 *
 * @author: aman
 * @since 2025-02-08
 */
@Slf4j
@Service
public class TicketInfoServiceImpl extends ServiceImpl<TicketInfoMapper, TicketInfoEntity> implements ITicketInfoService {

    @Resource
    private DeviceInfoMapper systemDeviceMapper;

    /**
     * @description 分页查询工单列表数据
     * @author aman
     * @date 2025/2/10 17:19
     */
    @Override
    public IPage<TicketInfoVo> getList(Page<TicketInfoEntity> page, TicketInfoDto ticketInfoDto) {
        LambdaQueryWrapper<TicketInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(ticketInfoDto)) {
            queryWrapper
                    .like(StrUtil.isNotBlank(ticketInfoDto.getStreamingNo()), TicketInfoEntity::getStreamingNo, ticketInfoDto.getStreamingNo())// 【流水号|订单号】字段进行模糊查询
                    .eq(ObjectUtil.isNotEmpty(ticketInfoDto.getOpFlag()), TicketInfoEntity::getOpFlag, ticketInfoDto.getOpFlag())// 【操作类别】字段进行精确查询
                    .eq(ObjectUtil.isNotEmpty(ticketInfoDto.getStatus()), TicketInfoEntity::getStatus, ticketInfoDto.getStatus())// 【工单状态】字段进行精确查询
                    .eq(ObjectUtil.isNotEmpty(ticketInfoDto.getProductType()), TicketInfoEntity::getProductType, ticketInfoDto.getProductType())// 【产品类型】字段进行精确查询
                    .eq(ObjectUtil.isNotEmpty(ticketInfoDto.getSource()), TicketInfoEntity::getSource, ticketInfoDto.getSource());// 【工单来源】字段进行精确查询
        }
        Page<TicketInfoEntity> ticketInfoPage = baseMapper.selectPage(page, queryWrapper);

        List<TicketInfoVo> ticketInfoVoList = ticketInfoPage.getRecords().stream().map(this::convertToTicketInfoVo).collect(Collectors.toList());
        IPage<TicketInfoVo> ticketInfoVoPage = new Page<>(ticketInfoPage.getCurrent(), ticketInfoPage.getSize(), ticketInfoPage.getTotal());
        ticketInfoVoPage.setRecords(ticketInfoVoList);
        return ticketInfoVoPage;
    }

    /**
     * @description 入库工单信息和设备信息
     * @author aman
     * @date 2025/2/10 18:18
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createTicketInfo(TicketInfoDto ticketInfoDto) {
        ticketInfoDto.setStatus(TicketStatusEnum.TS_INSERT);
        ticketInfoDto.setSource("ICT");
        log.info("开始入库工单下的设备信息、工单流水号:{}", ticketInfoDto.getStreamingNo());
        DeviceInfoEntity deviceInfoEntity = buildDeviceInfo(ticketInfoDto);
        systemDeviceMapper.insert(deviceInfoEntity);

        Integer deviceId = deviceInfoEntity.getId();
        log.info("开始入库工单信息、工单下的设备id：【{}】", deviceId);
        TicketInfoEntity ticketInfoEntity = buildTicketInfo(ticketInfoDto, deviceId);
        int insert = baseMapper.insert(ticketInfoEntity);
        if (insert < 1) {
            log.error("入库工单信息失败，工单流水号:{}", ticketInfoDto.getStreamingNo());
            return false;
        }
        log.info("入库工单及设备信息成功，工单数据ID:{}, 工单流水号:{}, 设备ID:{}", ticketInfoEntity.getId(), ticketInfoEntity.getStreamingNo(), deviceId);
        return true;
    }

    /**
     * @description 构建工单信息实体对象
     * @author aman
     * @date 2025/2/11 10:23
     */
    private static TicketInfoEntity buildTicketInfo(TicketInfoDto ticketInfoDto, Integer deviceId) {
        TicketInfoEntity ticketInfoEntity = new TicketInfoEntity();
        BeanUtil.copyProperties(ticketInfoDto, ticketInfoEntity);
        ticketInfoEntity.setDeviceId(deviceId);
        return ticketInfoEntity;
    }

    /**
     * @description 构建设备信息实体对象
     * @author aman
     * @date 2025/2/11 10:16
     */
    private static DeviceInfoEntity buildDeviceInfo(TicketInfoDto ticketInfoDto) {
        DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
        DeviceInfoDto device = ticketInfoDto.getDevice();
        BeanUtil.copyProperties(device, deviceInfoEntity);
        deviceInfoEntity.setMerchantName(ticketInfoDto.getMerchant().getMerchantName());
        deviceInfoEntity.setMerchantInfo(JSON.toJSONString(ticketInfoDto.getMerchant()));
        deviceInfoEntity.setDeviceProvince(device.getProvince());
        deviceInfoEntity.setDeviceCity(device.getCity());
        deviceInfoEntity.setDeviceCounty(device.getCounty());
        deviceInfoEntity.setDeviceAddress(device.getAddress());
        deviceInfoEntity.setIpsecIndex(100);
        deviceInfoEntity.setCreateTime(LocalDateTime.now());
        return deviceInfoEntity;
    }

    /**
     * @Description：工单实体转换为工单响应对象
     * @Author：aman
     * @Date：2025/1/27 12:22
     * @Param：systemTickets
     * @ParamsType：[com.example.fcmp.entity.SystemTickets]
     * @Return：com.example.fcmp.common.resp.SystemTicketsResp
     */
    private TicketInfoVo convertToTicketInfoVo(TicketInfoEntity ticketInfoEntity) {
        TicketInfoVo ticketInfoVo = new TicketInfoVo();
        BeanUtil.copyProperties(ticketInfoEntity, ticketInfoVo);
        return ticketInfoVo;
    }
}
